<script setup lang="ts">
import { ref, defineProps, defineEmits,onMounted,watch,toRaw } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import { addDeviceApi } from '@/api/products/device';
import { useLogic } from "@/views/system/user/logic/logic";
import {getDeviceGroupOptionsApi} from "@/api/products/deviceGroup";
import { getProductOptionsApi } from "@/api/products/product";
import { handleTree } from "@/utils/tree";
import { getNetworkTypeOptions, getProductOpenStatusOptions } from "@/utils/appCommon/appCommonOptions/products";
import UploadImg from "@/views/components/uploads/uploadImg.vue";
import {getDeviceOptionsApi} from "@/api/products/device";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const dialogVisible = ref(props.visible);
const emit = defineEmits(['update:visible', 'success','close']);
// 同步visible状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
}, { immediate: true });
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
  if (!newVal) emit('close');
});
// 产品选项数据
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const networkTypeOptions = ref([]);
const parentDeviceList = ref([]);
// 设备类型选项
const deviceTypeOptions = [
  { val: 0, label: t('products.productPage.directDevice') },
  { val: 1, label: t('products.productPage.gatewayDevice') },
  { val: 2, label: t('products.productPage.subDevice') }
];
onMounted(async () => {
  await getDeptTree()
  const productOptionsRes = await getProductOptionsApi()
  if(productOptionsRes.code == 0){
    productOptions.value = [
      ...productOptionsRes.data.options.map(option => ({
        val: option.val,
        label: option.label
      }))
    ];
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi()
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
  networkTypeOptions.value = await getNetworkTypeOptions()
})

// 批量表单数据
const batchForm = ref({
  prefix: '',
  startNum: '',
  endNum: '',
  generatedDevices: [] as string[]
});

// 基础表单数据（复用add.vue的字段）
const formData = ref({
  productId: 0,
  deptId: 0,
  groupId: null,
  type: 0,
  remark: '',
  lng: null,
  lat: null,
  address: '',
  image: '',
  openStatus: 0,
  parentId: null,
  networkType: 1
});

// 生成设备编号
const generateDevices = () => {
  const start = parseInt(batchForm.value.startNum);
  const end = parseInt(batchForm.value.endNum);
  const padLength = batchForm.value.startNum.length;

  batchForm.value.generatedDevices = [];
  for (let i = start; i <= end; i++) {
    const num = i.toString().padStart(padLength, '0');
    batchForm.value.generatedDevices.push(`${batchForm.value.prefix}${num}`);
  }
};

// 监听设备类型或部门ID变化，当类型为子设备时获取网关设备列表
watch([() => formData.value.type, () => formData.value.deptId], async () => {
  if (formData.value.type === 2 && formData.value.deptId) {
    try {
      const res = await getDeviceOptionsApi({
        type: "1", // 网关设备类型为1 为了避免直连类型0的误导，使用字符串
        deptId: formData.value.deptId,
        fieldKey: 'id',
        fieldLabel: 'name'
      });
      if (res.code === 0) {
        parentDeviceList.value = res.data.options || [];
      } else {
        parentDeviceList.value = [];
        ElMessage.error(res.msg || '获取网关设备失败');
      }
    } catch (error) {
      parentDeviceList.value = [];
      ElMessage.error('获取网关设备失败');
    }
  } else {
    parentDeviceList.value = [];
  }
}, { immediate: true });

// 提交批量新增
const submitBatch = async () => {
  try {
    for (const deviceNo of batchForm.value.generatedDevices) {
      await addDeviceApi({
        ...formData.value,
        deviceNo,
        name: deviceNo,
        channelNo: deviceNo
      });
    }
    ElMessage.success(t('products.devicePage.batchAddSuccess', { count: batchForm.value.generatedDevices.length }));
    emit('success');
    closeDialog();
  } catch (error) {
    ElMessage.error(t('products.devicePage.batchAddFailed'));
  }
};

const closeDialog = () => {
  emit('update:visible', false);
  batchForm.value = {
    prefix: '',
    startNum: '',
    endNum: '',
    generatedDevices: []
  };
};

const handleImgChange = (e:any)=> {
  console.log(e)
  formData.value.image = e
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('products.devicePage.batchAdd')"
    width="700px"
    :draggable="true"
    @close="closeDialog"
  >
    <el-form label-width="120px"  :model="formData">
      <el-form-item :label="t('products.devicePage.deviceNo')" required>
        <el-input v-model="batchForm.prefix" :placeholder="t('products.devicePage.prefixPlaceholder')" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.startNum')" required>
            <el-input v-model="batchForm.startNum" :placeholder="t('products.devicePage.startNumPlaceholder')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.endNum')" required>
            <el-input v-model="batchForm.endNum" :placeholder="t('products.devicePage.endNumPlaceholder')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="generateDevices">{{ t('products.devicePage.generateDevices') }}</el-button>
      </el-form-item>

      <el-form-item :label="t('products.devicePage.deviceNo')" v-if="batchForm.generatedDevices.length > 0">
        <div class="device-preview">
          <div v-for="(device, index) in batchForm.generatedDevices" :key="index" class="device-item">
            {{ device }}
          </div>
        </div>
      </el-form-item>

      <el-form-item :label="t('products.devicePage.productId')" prop="productId" required>
        <el-select v-model="formData.productId" :placeholder="t('products.devicePage.productId')">
          <el-option v-for="opt in productOptions" :key="opt.val" :label="opt.label" :value="opt.val" />
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.deptId')" prop="deptId">
            <el-cascader
              v-model="formData.deptId"
              class="w-full"
              :options="deptTreeList"
              :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
              clearable
              filterable
              :placeholder="t('products.devicePage.deptId')"
            >
              <template #default="{ node, data }">
                <span>{{ data.name }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.groupId')" prop="groupId">
            <el-cascader
              v-model="formData.groupId"
              class="w-full"
              :options="deviceGroupOptions"
              :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
              clearable
              filterable
              :placeholder="t('products.devicePage.groupId')"
            >
              <template #default="{ node, data }">
                <span>{{ data.name }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.openStatus')" prop="openStatus">
            <el-select v-model="formData.openStatus" placeholder="">
              <el-option :label="t('products.devicePage.notActivated')" :value="0"></el-option>
              <el-option :label="t('products.devicePage.activated')" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.productPage.deviceType')" prop="type" required>
            <el-select v-model="formData.type" :placeholder="t('products.productPage.selectDeviceType')">
              <el-option
                v-for="option in deviceTypeOptions"
                :key="option.val"
                :label="option.label"
                :value="option.val"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.type == 2">
          <el-form-item v-if="formData.type == 2" :label="t('products.devicePage.parentDevice')" prop="parentId">
            <el-select v-model.number="formData.parentId" :placeholder="t('products.devicePage.selectParentDevice')" clearable>
              <el-option
                v-for="option in parentDeviceList"
                :key="option.val"
                :label="option.label"
                :value="option.val"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.lng')" prop="lng">
            <el-input v-model.number="formData.lng" :placeholder="t('products.devicePage.lngPlaceholder')" type="number" step="0.00000001" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.lat')" prop="lat">
            <el-input v-model.number="formData.lat" :placeholder="t('products.devicePage.latPlaceholder')" type="number" step="0.00000001" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="t('products.devicePage.address')" prop="address">
        <el-input v-model="formData.address" :placeholder="t('products.devicePage.addressPlaceholder')" />
      </el-form-item>

      <el-form-item :label="t('products.devicePage.image')" prop="image" required>
        <upload-img v-model:imgUrl="formData.image" @change="handleImgChange" />
        <div class="upload-hint">{{ t('products.devicePage.uploadImgHint') }}</div>
      </el-form-item>

      <el-form-item :label="t('products.devicePage.remark')" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :placeholder="t('products.devicePage.remarkPlaceholder')" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('products.devicePage.networkType')" prop="networkType">
            <el-select v-model="formData.networkType" :placeholder="t('products.devicePage.networkType')">
              <el-option :label="o.label" :value="o.val" v-for="(o,i) in networkTypeOptions" :key="i"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">{{ t('buttons.cancel') }}</el-button>
      <el-button type="primary" @click="submitBatch">{{ t('products.devicePage.submitBatchAdd') }}</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.device-preview {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;

  .device-item {
    padding: 8px;
    margin: 4px 0;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}
</style>
